package com.lou1052.redis.jedis.action.script;

import com.google.common.collect.Lists;
import com.lou1052.redis.jedis.api.ScriptCommands;

import java.util.List;

/**
 * 不存在则set返回 存在则get返回
 * Created with IntelliJ IDEA.
 * User: liuqing
 * Date: 2015/11/16
 * Time: 22:17
 * To change this template use File | Settings | File Templates.
 */
public class SetNxOrGetObjectAction  extends ScriptAction<Object>{

    private static final String SCRIPT="local v = redis.call('get',KEYS[1]);if v then return v;else redis.call('set',KEYS[1],ARGV[1]);return ARGV[1];end";

    private final Object initValue;

    public SetNxOrGetObjectAction(String key ,Object initValue) {
        super(key);
        this.initValue=initValue;
    }

    @Override
    public Object callOn(ScriptCommands scriptCommands) {
        List<Object> params = Lists.newArrayList(initValue);
        return scriptCommands.eval(SCRIPT,getKey(),params);
    }
}
